<!-- 流程发起页面 -->
<template>
    <div class="start-process">
        <el-card class="process-card">
            <template #header>
                <div class="card-header">
                    <span>发起任务</span>
                    <el-button type="danger" link @click="handleClose">关闭</el-button>
                </div>
            </template>

            <el-tabs v-model="activeTab">
                <el-tab-pane label="表单信息" name="form">
                    <div v-loading="formLoading">
                        <v-form-render v-if="formJson" ref="formRef" :form-json="parsedFormJson" :form-data="formData"
                            :option-data="optionData" @submit="handleSubmit" />
                        <div v-else class="no-form">
                            <el-empty description="暂无表单数据" />
                        </div>
                    </div>
                    <div class="form-actions">
                        <el-button type="primary" @click="submitForm">提交</el-button>
                        <el-button @click="resetForm">重置</el-button>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="流程图" name="flow">
                    <div class="flow-chart" v-loading="flowLoading">
                        <div class="bpmn-preview" v-if="bpmnXml">
                            <div ref="bpmnContainer" class="bpmn-container" style="width: 100%; height: 100%;"></div>
                        </div>
                        <el-empty v-else description="暂无流程图数据" />
                    </div>
                </el-tab-pane>
            </el-tabs>
        </el-card>
    </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { VFormRender } from 'vform3-builds'
import BpmnViewer from 'bpmn-js/lib/Viewer'
import 'bpmn-js/dist/assets/diagram-js.css'
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css'

export default {
    name: 'StartProcess',

    components: {
        VFormRender
    },

    props: {
        processInfo: {
            type: Object,
            required: true
        }
    },

    data() {
        return {
            activeTab: 'form',
            formLoading: false,
            flowLoading: false,
            formJson: null,
            formData: {},
            optionData: {},
            bpmnViewer: null,
            bpmnXml: null,
            isFlowInitialized: false  // 新增：标记流程图是否已初始化
        }
    },

    computed: {
        parsedFormJson() {
            if (typeof this.formJson === 'string') {
                try {
                    return JSON.parse(this.formJson)
                } catch (e) {
                    console.error('解析表单JSON失败：', e)
                    return null
                }
            }
            return this.formJson
        }
    },

    watch: {
        activeTab: {
            immediate: true,
            async handler(newVal) {
                if (newVal === 'flow' && !this.isFlowInitialized) {
                    await this.initFlowChart()
                }
                // 当切换到流程图标签页时，重新调整视图
                if (newVal === 'flow' && this.bpmnViewer) {
                    await this.$nextTick()
                    const canvas = this.bpmnViewer.get('canvas')
                    canvas.zoom('fit-viewport')
                }
            }
        }
    },

    mounted() {
        this.initForm()
    },

    beforeUnmount() {
        if (this.bpmnViewer) {
            this.bpmnViewer.destroy()
            this.bpmnViewer = null // 防止内存泄漏
        }
    },

    methods: {
        // 处理表单提交
        handleSubmit(formData) {
            console.log('表单提交数据：', formData)
            // 这里可以添加表单提交前的验证逻辑
        },

        // 初始化表单
        async initForm() {
            this.formLoading = true
            try {
                console.log('开始获取表单数据，processInfo:', this.processInfo)
                const res = await this.$get('/getProcessForm', {
                    id: this.processInfo.id
                })
                console.log('获取到的表单数据:', res)
                if (res.data) {
                    // 确保formJson是对象类型
                    this.formJson = typeof res.data.formJson === 'string' ? JSON.parse(res.data.formJson) : res.data.formJson
                    this.formData = {}  // 初始化表单数据
                    this.optionData = {} // 初始化选项数据
                    console.log('设置后的表单数据:', {
                        formJson: this.formJson,
                        formData: this.formData,
                        optionData: this.optionData
                    })
                }
            } catch (err) {
                console.error('获取表单数据失败：', err)
                ElMessage.error('获取表单数据失败')
            } finally {
                this.formLoading = false
            }
        },

        // 初始化流程图
        async initFlowChart() {
            if (this.bpmnXml || this.flowLoading || this.isFlowInitialized) return

            this.flowLoading = true
            try {
                console.log('开始获取流程图数据，processInfo:', this.processInfo)
                const res = await this.$get('/getProcessBpmn', {
                    id: this.processInfo.id
                })
                console.log('获取到的流程图数据:', res)

                if (!res || res.code !== 200) {
                    throw new Error('获取流程图数据失败：' + (res?.msg || '未知错误'))
                }

                if (!res.data) {
                    throw new Error('未获取到流程图数据')
                }

                // 增强XML验证
                if (typeof res.data !== 'string' || !res.data.includes('<?xml')) {
                    throw new Error('无效的BPMN XML数据')
                }

                // 验证BPMN命名空间
                // if (!/xmlns:bpmn="http:\/\/www\.omg\.org\/spec\/BPMN\/20100524\/MODEL"/.test(res.data)) {
                //   throw new Error('BPMN XML缺少必要命名空间')
                // }

                this.bpmnXml = res.data

                // 等待DOM更新并确保容器可见
                await this.$nextTick()
                const container = this.$refs.bpmnContainer

                if (!container) {
                    throw new Error('BPMN容器元素不存在')
                }

                // 检查容器是否可见
                if (container.clientWidth === 0) {
                    console.warn('容器不可见，延迟初始化')
                    setTimeout(() => this.initBpmnViewer(this.bpmnXml), 300)
                    return
                }

                await this.initBpmnViewer(this.bpmnXml)
                this.isFlowInitialized = true

            } catch (err) {
                console.error('获取或初始化流程图失败：', err)
                if (err.warnings?.length) {
                    err.warnings.forEach(w => console.warn('XML警告:', w))
                }
                ElMessage.error('获取或初始化流程图失败：' + (err.message || '未知错误'))
                this.bpmnXml = null
            } finally {
                this.flowLoading = false
            }
        },

        // 初始化BPMN查看器
        async initBpmnViewer(bpmnXml) {
            console.log('initBpmnViewer开始执行，XML长度:', bpmnXml.length)

            if (!bpmnXml) {
                console.error('BPMN XML数据为空')
                return
            }

            const container = this.$refs.bpmnContainer
            if (!container) {
                console.error('找不到流程图容器元素')
                return
            }

            try {
                if (this.bpmnViewer) {
                    this.bpmnViewer.destroy()
                    this.bpmnViewer = null
                }

                this.bpmnViewer = new BpmnViewer({
                    container: container
                })

                const result = await this.bpmnViewer.importXML(bpmnXml)

                if (result.warnings?.length) {
                    console.warn('BPMN导入警告:', result.warnings)
                }

                const canvas = this.bpmnViewer.get('canvas')
                canvas.zoom('fit-viewport')

                ElMessage.success('流程图加载成功')
            } catch (err) {
                console.error('BPMN查看器初始化失败:', err)
                if (err.warnings?.length) {
                    err.warnings.forEach(w => console.warn('XML警告:', w))
                }
                throw new Error('BPMN查看器初始化失败: ' + (err.message || '未知错误'))
            }
        },
        // 提交表单
        submitForm() {
            if (!this.$refs.formRef) {
                ElMessage.warning('请先填写表单')
                return
            }

            const formData = this.$refs.formRef.getFormData()
            const submitData = {
                processDefinitionId: this.processInfo.id,
                formData: formData
            }
            console.log("设置后的表单===========");
            
            console.log(formData);
            this.$post('/startTask', submitData).then(res => {
                if (res.code == 200) {
                    ElMessage.success('流程发起成功')
                    this.$emit('success')
                    
                }else{
                    ElMessage.error(res.msg)
                    this.$emit('danger')
                }
                

            }).catch(err => {
                const errorMsg = err.message || '请将表单信息补充完整'
                console.error('提交失败：', err)
                ElMessage.error('提交失败：' + errorMsg)
            })
        },

        // 重置表单
        resetForm() {
            if (this.$refs.formRef) {
                this.$refs.formRef.resetForm()
            }
        },

        // 关闭页面
        handleClose() {
            this.$emit('close')
        }
    }
}
</script>

<style lang="scss" scoped>
.start-process {
    padding: 20px;
    height: 100%;
    box-sizing: border-box;

    .process-card {
        height: 100%;
        display: flex;
        flex-direction: column;

        :deep(.el-card__body) {
            flex: 1;
            overflow: auto;
            padding: 20px;
        }
    }

    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .no-form {
        padding: 40px 0;
    }

    .flow-chart {
        height: 600px;
        position: relative;

        .bpmn-preview {
            width: 100%;
            height: 100%;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            background-color: #fff;
            position: relative;
        }

        .bpmn-container {
            width: 100%;
            height: 100%;
            position: relative;
            overflow: hidden;

            /* 增加样式权重，确保BPMN查看器样式不被覆盖 */
            :deep(.djs-container) {
                height: 100% !important;
                width: 100% !important;
                position: absolute !important;
                top: 0 !important;
                left: 0 !important;
                overflow: hidden !important;
                z-index: 1 !important;
            }

            :deep(.djs-palette) {
                display: none !important;
            }

            :deep(.djs-context-pad) {
                display: none !important;
            }

            :deep(.djs-overlay-context-pad) {
                display: none !important;
            }

            :deep(.djs-element) {
                cursor: default !important;
                pointer-events: none !important;
                fill-opacity: 1 !important;
            }

            :deep(.djs-connection) {
                cursor: default !important;
                pointer-events: none !important;
            }

            :deep(.djs-shape) {
                cursor: default !important;
                pointer-events: none !important;
            }

            :deep(.djs-label) {
                font-size: 14px !important;
                font-weight: bold !important;
                fill: #303133 !important;
                pointer-events: none !important;
                display: block !important;
                visibility: visible !important;
                opacity: 1 !important;
            }

            :deep(.djs-label text) {
                font-size: 14px !important;
                font-weight: bold !important;
                fill: #303133 !important;
                pointer-events: none !important;
            }
        }
    }

    .form-actions {
        margin-top: 20px;
        text-align: center;
    }
}

/* 移除全局样式，改为嵌套在.bpmn-container中 */
</style>